package com.tianya.forum.service.impl;

import com.tianya.forum.common.AppResult;
import com.tianya.forum.common.ResultCode;
import com.tianya.forum.dao.ArticleMapper;
import com.tianya.forum.exception.ApplicationException;
import com.tianya.forum.model.Article;
import com.tianya.forum.model.Board;
import com.tianya.forum.model.User;
import com.tianya.forum.service.IArticleService;
import com.tianya.forum.service.IBoardService;
import com.tianya.forum.service.IUserService;
import com.tianya.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private IUserService userService;

    @Resource
    private IBoardService boardService;

    /**
     * 发布帖子
     * @param article
     */
    @Transactional
    public void create(Article article){
        //非空校验
        if(article == null || article.getBoardId() == null
                || article.getUserId() == null
                || StringUtil.isEmpty(article.getTitle())
                || StringUtil.isEmpty(article.getContent())
                 ){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //设置默认值
        article.setVisitCount(0);
        article.setReplyCount(0);
        article.setLikeCount(0);
        article.setState((byte) 0);
        article.setDeleteState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);

        //写入数据库帖子表
        int row = articleMapper.insertSelective(article);
        if(row <= 0){
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

        //更新用户发帖数
        User user = userService.selectById(article.getUserId());
        if(user == null){
            log.warn(ResultCode.FAILED_CREATE.toString() + ", 发贴失败, user id = " + article.getUserId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));

        }
        userService.addArticleCountById(article.getUserId());

        //更新版块贴子数
        Board board = boardService.selectById(article.getBoardId());
        if(board == null){
            log.warn(ResultCode.FAILED_CREATE.toString() + ", 发帖失败， board id =" + article.getBoardId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        //校验版块是否禁用
        if(board.getState() == 1){
            log.warn(ResultCode.FAILED_BOARD_FORBIDDEN.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_FORBIDDEN));
        }
        boardService.addArticleCountById(article.getBoardId());

        //发帖成功打印⽇志
        log.info(ResultCode.SUCCESS.toString() + ", user id = " +
                article.getUserId()
                + ", board id = " + article.getBoardId() + ", article id = "+article.getId() + "发帖成功");
    }

    /**
     * 在主页中显示帖子列表以发布时间降序排列
     * @return 帖子列表
     */
    public List<Article> selectAll(){
        List<Article> result = articleMapper.selectAll();
        return result;
    }

    /**
     * 根据版块Id查询帖⼦列表以发布时间降序排列
     *
     * @param boardId 版块Id
     * @return 帖⼦列表
     */
    @Override
    public List<Article> selectByBoardId(Long boardId) {
        //非空检验
        if(boardId == null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //利用DAO层查询结果
        List<Article> result = articleMapper.selectByBoardId(boardId);
        return result;
    }

    /**
     * 根据帖子ID显示帖子详情
     * @param id 帖子ID
     * @return 帖子详情
     */
    @Override
    public Article selectDetailById(Long id) {
        //非空校验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询帖子
        Article article = articleMapper.selectDetailById(id);
        if(article == null){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //更新帖子访问量
        Article article1 = articleMapper.selectByPrimaryKey(id);
        Article update = new Article();
        update.setId(article1.getId());
        update.setVisitCount(article1.getVisitCount()+1);
        int row = articleMapper.updateByPrimaryKeySelective(update);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES ));
        }
        //更新帖子对象的访问量
        article.setVisitCount(article.getVisitCount()+1);
        return article;
    }

    /**
     * 根据帖子ID查询帖子
     * @param id 帖子ID
     * @return 帖子对象
     **/
    @Override
    public Article selectById(Long id) {
        //非空校验
        if(id == null || id <=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO
        Article article = articleMapper.selectByPrimaryKey(id);
        //返回结果
        return article;
    }

    /**
     * 更新帖子
     * @param id 帖子ID
     * @param title 标题
     * @param content 正文
     */
    @Override
    public void modify(Long id, String title, String content) {
        // ⾮空校验
        if (id == null || StringUtil.isEmpty(title) ||
                StringUtil.isEmpty(content)) {
            // 记录⽇志
            log.info(ResultCode.ERROR_IS_NULL.toString());
            // 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        // 构造帖⼦对象
        Article update = new Article();
        update.setId(id);
        update.setTitle(title);
        update.setContent(content);
        update.setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(update);
        if (row != 1) {
            // 记录⽇志
            log.info(ResultCode.ERROR_SERVICES.toString() + "articleId = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    /**
     * 点赞帖子
     * @param id 帖子ID
     */
    @Override
    public void thumbsUpById(Long id) {
        // ⾮空校验
        if (id == null) {
            // 记录⽇志
            log.info(ResultCode.ERROR_IS_NULL.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        // 查询帖⼦信息
        Article article = selectById(id);
        if (article == null || article.getState() == 1 || article.getDeleteState() == 1) {
            // FAILED_NOT_EXISTS
            // 记录⽇志
            log.info(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 构造更新对象
        Article update = new Article();
        update.setId(article.getId());
        update.setLikeCount(article.getLikeCount() + 1);
        // 更新数据库
        int row = articleMapper.updateByPrimaryKeySelective(update);
        if (row != 1) {
            // 记录⽇志
            log.info(ResultCode.FAILED.toString() + "userId = " + article.getUserId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_LIKE));
        }
    }

    /**
     * 删除帖子
     * @param id 帖子ID
     */
    @Override
    public void deleteById(Long id) {
        // ⾮空校验
        if (id == null) {
            // 记录⽇志
            log.info(ResultCode.ERROR_IS_NULL.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        // 查询帖⼦信息
        Article article = articleMapper.selectByPrimaryKey(id);
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setDeleteState((byte) 1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            log.warn(ResultCode.FAILED_ARTICLE_DELETE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_DELETE ));
        }
        //更新版块中的帖子数量
        boardService.subOneArticleCountById(article.getBoardId());
        //更新用户中的贴子数
        userService.subOneArticleCountById(article.getUserId());
    }

    /**
     * 更新帖子回复数（+1）
     * @param id 帖子id
     */
    @Override
    public void addOneReplyCount(Long id) {
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article == null || article.getState() == 1 || article.getDeleteState() ==1){
            log.warn(ResultCode.FAILED_ARTICLE_FORBIDDEN.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_FORBIDDEN));
        }
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setReplyCount(article.getReplyCount()+1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            // 记录⽇志
            log.info("帖⼦回复数量更新失败, userId = " );
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        if(userId == null || userId<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userService.selectById(userId);
        //判断用户是否存在
        if(user == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 调⽤DAO层查询结果
        List<Article> result = articleMapper.selectByUserId(userId);
        // 返回结果
        return result;
    }
}
